﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;

using Finance.Entites;

namespace Finance.UI.ViewModels
{
    public class PeriodicDetailGroupViewModel : ObservableCollection<Charge>
    {
        public DateTime _Key;
        public DateTime Key
        {
            get { return ToShortDate(_Key); }
            set
            {
                _Key = ToShortDate(value);
                OnPropertyChanged(new PropertyChangedEventArgs("Key"));
            }
        }

        public PeriodicDetailGroupViewModel(DateTime datetime)
        {
            Key = datetime;
            Func<Charge, bool> predicate =
                c =>
                {
                    return ToShortDate(c.Date).Equals(ToShortDate(datetime));
                };
            foreach (var item in App.ChargeDataStore.Items.Where(predicate))
            {
                this.Add(item);
            }
            App.ChargeDataStore.Items.CollectionChanged +=
                (o, e) =>
                {
                    switch (e.Action)
                    {
                        case NotifyCollectionChangedAction.Add:
                            {
                                var item = e.NewItems[0] as Charge;
                                if (predicate(item))
                                {
                                    this.Add(item);
                                }
                            }
                            break;
                        case NotifyCollectionChangedAction.Remove:
                            {
                                var item = e.OldItems[0] as Charge;
                                if (this.Contains(item))
                                {
                                    this.Remove(item);
                                }
                            } break;
                        default: break;
                    }
                };
        }

        public override int GetHashCode()
        {
            //return Key.Year * 10000000 + Key.Month * 100 + Key.Day;
            return base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (!(obj is PeriodicDetailGroupViewModel))
            {
                return false;
            }
            else
            {
                return (obj as PeriodicDetailGroupViewModel).Key.Equals(this.Key);
            }
        }

        private DateTime ToShortDate(DateTime datetime)
        {
            return new DateTime(datetime.Year, datetime.Month, datetime.Day);
        }
    }
}
